package com.xnfh.login

import android.os.Build
import android.text.Editable
import android.text.SpannableStringBuilder
import android.text.Spanned
import android.text.TextPaint
import android.text.TextUtils
import android.text.TextWatcher
import android.text.method.LinkMovementMethod
import android.text.style.ClickableSpan
import android.view.View
import android.view.View.OnLongClickListener
import android.view.inputmethod.InputMethodManager
import android.widget.TextView
import androidx.annotation.RequiresApi
import androidx.lifecycle.lifecycleScope
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.xnfh.common.constant.ArouterPath
import com.xnfh.common.constant.KvKey
import com.xnfh.common.manager.UserInfoManager
import com.xnfh.framework.base.BaseActivity
import com.xnfh.framework.base.BaseStateObserver
import com.xnfh.framework.bean.UserInforBean
import com.xnfh.framework.ext.countDownCoroutines
import com.xnfh.framework.log.LogUtil
import com.xnfh.framework.toast.TipsToast
import com.xnfh.framework.utils.AppExit
import com.xnfh.framework.utils.FormatUtil
import com.xnfh.framework.utils.KVUtil
import com.xnfh.framework.utils.getColorFromResource
import com.xnfh.framework.utils.getStringFromResource
import com.xnfh.login.databinding.ActivityLoginLayoutBinding
import com.xnfh.login.viewmodel.LoginViewModel

/**
 * @Description:登录页面
 * @Author: ziheng
 * @CreateDate: 2023/11/8 09:16
 * @UpdateUser: ziheng
 * @UpdateDate: 2023/11/8 09:16
 * @UpdateRemark: 更新说明
 */
@Route(path = ArouterPath.LOGIN.LOGIN_ACTIVITY)
class LoginActivity : BaseActivity<ActivityLoginLayoutBinding>(),View.OnClickListener {
    override fun getLayoutID(): Int = R.layout.activity_login_layout

    private var isReadUserAgreement = false
    private lateinit var viewModel: LoginViewModel

    override fun init() {
        initAgreement()
        observeLoginButtonBg()
        mBind.loginSendCode.setOnClickListener(this)
        mBind.loginGologinBut.setOnClickListener(this)
        mBind.loginCheck.setOnClickListener(this)
        mBind.loginAppIcon.setOnLongClickListener {
            SettingConfigActivity.start(this)
            true
        }
    }

    override fun observe() {
        viewModel = LoginViewModel()
        //发送验证码
        viewModel.sendCodeBean.observe(this,object: BaseStateObserver<String>(){
            override fun getRespDataSuccess(it: String) {
                super.getRespDataSuccess(it)
                TipsToast.showTips(it)
                countDownCoroutines(60, lifecycleScope, onTick = {
                    mBind.loginSendCode.text = "${it}s${getStringFromResource(R.string.str_agin_send_code_end)}"
                }){
                    mBind.loginSendCode.text = getStringFromResource(R.string.str_agin_send_code)
                }
            }
        })
        //判断验证码是否正确
        viewModel.checkSmsCodeBean.observe(this,object : BaseStateObserver<String>(){
            override fun getRespDataSuccess(it: String) {
                super.getRespDataSuccess(it)
                viewModel.requestLogin(mBind.loginPhone.text.toString())
            }
        })
        viewModel.loginBean.observe(this,object :BaseStateObserver<UserInforBean>(){
            override fun getRespDataSuccess(it: UserInforBean) {
                super.getRespDataSuccess(it)
                UserInfoManager.instance.updateUserInfor(it)
                ARouter.getInstance().build(ArouterPath.HOME.MAIN_ACTIVITY).navigation()
                finish()
            }
        })
    }

    override fun onClick(v: View?) {
        when(v){
            mBind.loginSendCode ->{
                if(!FormatUtil.isMobileNO(mBind.loginPhone.text.toString())){
                    TipsToast.showTips(R.string.str_qsrzqd_sjh)
                    return
                }
                viewModel.requestSendCode(mBind.loginPhone.text.toString())
            }
            mBind.loginGologinBut ->{
                if(!FormatUtil.isMobileNO(mBind.loginPhone.text.toString())){
                    TipsToast.showTips(R.string.str_qsrzqd_sjh)
                    return
                }
                //如果是免验，直接登录
                if(KVUtil.getBoolean(SettingConfigActivity.MIAN_YAN,false)){
                    viewModel.requestLogin(mBind.loginPhone.text.toString())
                    return
                }
                if(mBind.loginCode.text.toString().isEmpty()){
                    TipsToast.showTips(R.string.str_qsr_yzm)
                    return
                }
                if(!isReadUserAgreement){
                    val imm = getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager
                    imm.hideSoftInputFromWindow(v.windowToken, 0) //强制隐藏键盘
                    TipsToast.showTips(R.string.tips_read_user_agreement)
                    return
                }
                viewModel.requestCheckSmsCode(mBind.loginPhone.text.toString(),mBind.loginCode.text.toString())
            }
            mBind.loginCheck ->{
                isReadUserAgreement = !isReadUserAgreement
                if(isReadUserAgreement){
                    mBind.loginCheck.setImageResource(R.mipmap.xuanzeyi)
                }else{
                    mBind.loginCheck.setImageResource(R.mipmap.checkbox_bg_default)
                }
            }
        }
    }

    /**
     * 控制登录按钮是否可以点击
     */
    private fun observeLoginButtonBg() {
        mBind.loginCode.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {

            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                if ((!TextUtils.isEmpty(s.toString().trim { it <= ' ' }) && s.toString()
                        .trim { it <= ' ' }.length == 6  && mBind.loginPhone.text.toString().length == 11) || KVUtil.getBoolean(SettingConfigActivity.MIAN_YAN,false)) {
                    mBind.loginGologinBut.isClickable = true
                    mBind.loginGologinBut.setBackgroundResource(R.drawable.user_login_select_shape)
                    mBind.loginGologinBut.setTextColor(resources.getColor(R.color.white))
                } else {
                    mBind.loginGologinBut.isClickable = false
                    mBind.loginGologinBut.setBackgroundResource(R.drawable.user_login_shape)
                    mBind.loginGologinBut.setTextColor(resources.getColor(R.color.color_B9C1CA))
                }
            }

            override fun afterTextChanged(s: Editable?) {

            }

        })
        mBind.loginPhone.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {

            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                if (!TextUtils.isEmpty(s.toString().trim { it <= ' ' }) && s.toString()
                        .trim { it <= ' ' }.length == 11 && (mBind.loginCode.text.toString().length == 6 || KVUtil.getBoolean(SettingConfigActivity.MIAN_YAN,false))) {
                    mBind.loginGologinBut.isClickable = true
                    mBind.loginGologinBut.setBackgroundResource(R.drawable.user_login_select_shape)
                    mBind.loginGologinBut.setTextColor(resources.getColor(R.color.white))
                } else {
                    mBind.loginGologinBut.isClickable = false
                    mBind.loginGologinBut.setBackgroundResource(R.drawable.user_login_shape)
                    mBind.loginGologinBut.setTextColor(resources.getColor(R.color.color_B9C1CA))
                }
            }

            override fun afterTextChanged(s: Editable?) {
            }

        })
    }


    /**
     * 初始化协议点击
     */
    private fun initAgreement() {
        val agreement = getStringFromResource(R.string.login_agreement)
        try {
            mBind.loginAgreement.movementMethod = LinkMovementMethod.getInstance()
            val spaBuilder = SpannableStringBuilder(agreement)
            val privacySpan = getStringFromResource(R.string.login_privacy_agreement)
            val serviceSpan = getStringFromResource(R.string.login_user_agreement)
            spaBuilder.setSpan(
                object : ClickableSpan() {
                    override fun onClick(widget: View) {
                        (widget as TextView).highlightColor = getColorFromResource(R.color.transparent)
                        TipsToast.showTips("用户协议")
//                        PrivacyPolicyActivity.start(this@LoginActivity)
                    }

                    @RequiresApi(Build.VERSION_CODES.M)
                    override fun updateDrawState(ds: TextPaint) {
                        super.updateDrawState(ds)
                        ds.color = getColorFromResource(R.color.color_00C358)
                        ds.isUnderlineText = false
                        ds.clearShadowLayer()
                    }
                },
                spaBuilder.indexOf(privacySpan),
                spaBuilder.indexOf(privacySpan) + privacySpan.length,
                Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
            )
            spaBuilder.setSpan(
                object : ClickableSpan() {
                    override fun onClick(widget: View) {
                        (widget as TextView).highlightColor = getColorFromResource(R.color.transparent)
                        TipsToast.showTips("隐私政策")
//                        PrivacyPolicyActivity.start(this@LoginActivity)
                    }

                    @RequiresApi(Build.VERSION_CODES.M)
                    override fun updateDrawState(ds: TextPaint) {
                        super.updateDrawState(ds)
                        ds.color = getColorFromResource(R.color.color_00C358)
                        ds.isUnderlineText = false
                        ds.clearShadowLayer()
                    }
                },
                spaBuilder.indexOf(serviceSpan),
                spaBuilder.indexOf(serviceSpan) + serviceSpan.length,
                Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
            )

            mBind.loginAgreement.setText(spaBuilder, TextView.BufferType.SPANNABLE)
        } catch (e: Exception) {
            LogUtil.e(e)
            mBind.loginAgreement.text = agreement
        }
    }

    override fun onBackPressed() {
        AppExit.onBackPressed(
            this,
            { TipsToast.showTips(getString(com.xnfh.framework.R.string.base_app_exit_one_more_press)) }
        )
    }
}